package com.qiantu.phone.ui.fragment.device;

import android.graphics.Color;
import android.view.View;
import android.widget.ImageView;

import androidx.lifecycle.LifecycleOwner;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hjq.base.BaseAdapter;
import com.hjq.http.listener.HttpCallback;
import com.hjq.toast.ToastUtils;
import com.qiantu.api.db.LLDeviceDBManager;
import com.qiantu.api.entity.ControlDataColorTemperatureBean;
import com.qiantu.api.entity.DeviceState;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.api.utils.DeviceInfoParseUtil;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.ui.adapter.ColorTemperatureAdapter;
import com.qiantu.phone.ui.uiutil.LLDeviceUtil;
import com.qiantu.phone.widget.ColorDevicePalette;
import com.qiantu.phone.widget.ColorDeviceSeekBar;
import com.qiantu.phone.widget.ColorTemperatureSeekBar;
import com.qiantu.phone.widget.ColorWhiteSeekBar;

import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;

public class ColorDeviceFragment extends BaseDeviceFragment{

    private ColorDevicePalette devicePalette;
    private RecyclerView colorRecyclerView;
    private ColorTemperatureAdapter mColorTemperatureAdapter;
    private ColorWhiteSeekBar colorWhiteSeekBar;
    private ColorWhiteSeekBar colorTemperatureSeekBar;
    private ImageView btnPower;
    private ControlDataColorTemperatureBean mColorTemperatureInfo;
    private ControlDataColorTemperatureBean.ControlData controlData;

    public static ColorDeviceFragment newInstance() {
        ColorDeviceFragment fragment = new ColorDeviceFragment();
        return fragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_color_device;
    }

    @Override
    protected void initView() {
        super.initView();
        devicePalette = findViewById(R.id.round_seek_bar);
        colorRecyclerView = findViewById(R.id.color_recycler_view);
        colorWhiteSeekBar = findViewById(R.id.color_white_seek_bar);
        colorTemperatureSeekBar = findViewById(R.id.color_temperature_seek_bar);
        btnPower = findViewById(R.id.btn_power);
        btnPower.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switchOperation(mDevice.getIsOpen() ? 0 : 1);
            }
        });
        devicePalette.setOnPaletteChangeListener(new ColorDevicePalette.OnPaletteChangeListener() {
            @Override
            public void onValueChanged(int colorValue) {}
            @Override
            public void onStartTrackingTouch() { }

            @Override
            public void onStopTrackingTouch(int colorValue) {
                changeColor(colorValue);
            }
        });
        colorWhiteSeekBar.setOnSeekBarChangeListener(new ColorTemperatureSeekBar.OnSeekBarChangeListener() {
            @Override
            public void onValueChanged(int colorTemp) {}
            @Override
            public void onStartTrackingTouch() { }

            @Override
            public void onStopTrackingTouch(int colorTemp) {
                if(colorTemp == 0){
                    switchOperation(0);
                }else{
                    lightOperation(colorTemp);
                }
            }
        });
        colorTemperatureSeekBar.setOnSeekBarChangeListener(new ColorTemperatureSeekBar.OnSeekBarChangeListener() {
            @Override
            public void onValueChanged(int colorTemp) {}
            @Override
            public void onStartTrackingTouch() { }

            @Override
            public void onStopTrackingTouch(int colorTemp) {
                if(colorTemp == 0){
                    switchOperation(0);
                }else{
                    lightOperation(colorTemp);
                }
            }
        });
        mColorTemperatureInfo = DeviceInfoParseUtil.parseData(getContext(), mDevice.getDeviceType(), ControlDataColorTemperatureBean.class);
        controlData = mColorTemperatureInfo.getControlData();
        if(controlData.getColorData() != null && controlData.getColorData().size() > 0){
            mColorTemperatureAdapter = new ColorTemperatureAdapter(getContext());
            mColorTemperatureAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
                    if(mDevice.getIsOpen()){
                        mColorTemperatureAdapter.selectItem(position);
                        ControlDataColorTemperatureBean.ColorData colorData = mColorTemperatureAdapter.getData().get(position);
                        changeColor(colorData.getColor());
                    }
                }
            });
            colorRecyclerView.setAdapter(mColorTemperatureAdapter);
            GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), controlData.getColorData().size());
            colorRecyclerView.setLayoutManager(gridLayoutManager);
            mColorTemperatureAdapter.setData(controlData.getColorData());
        }
        updateView();
    }

    private void setStatusBySwitch(boolean isOpen){
        colorWhiteSeekBar.setOpenState(isOpen);
        colorTemperatureSeekBar.setOpenState(isOpen);
        devicePalette.setOpenState(isOpen);
        btnPower.setImageResource(isOpen ? R.mipmap.icon_devicecontrol_curtain_switch_open : R.mipmap.icon_devicecontrol_curtain_switch_close);
    }

    protected void updateView(){
        super.updateView();
        DeviceState deviceState = mDevice.getStateData();
        Integer light = deviceState.getStatus().getLight();
//        devicePalette.setEnabled(mDevice.getIsOpen());
        Float progress = Float.valueOf(light);
        colorTemperatureSeekBar.setColorValue(light);
        //如果设备亮度0的话，本地强制设置灯关
        setStatusBySwitch(progress == 0 ? false : mDevice.getIsOpen());
    }

    private void switchOperation(int power){
        Map<String, Object> option = new HashMap<>();
        option.put(LLDeviceUtil.POWER, power);
        Map<String, Object> status = new HashMap<>();
        status.put(STATUS, option);

        HttpCallback<HttpData<Void>> callback = new HttpCallback<HttpData<Void>>(null) {
            @Override
            public void onStart(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity){
                    ((AppActivity) getContext()).showDialog("执行中...");
                }
            }

            @Override
            public void onSucceed(HttpData<Void> result) {
                mDevice.setIsOpen(!mDevice.getIsOpen());
                setStatusBySwitch(mDevice.getIsOpen());
                LLDeviceDBManager.getInstance(getContext()).put(mDevice);
                refreshDeviceStateByLocal();
            }

            @Override
            public void onFail(Exception e) {
                ToastUtils.show(R.string.exec_failure);
            }

            @Override
            public void onEnd(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity) {
                    ((AppActivity) getContext()).hideDialog();
                }
            }
        };

        LLHttpManager.operationDevice((LifecycleOwner) getContext(), mDevice.getDeviceSerialNo(), status, callback);
    }

    private void lightOperation(int light){
        Map<String, Object> option = new HashMap<>();
        option.put(LLDeviceUtil.LIGHT, light);
        Map<String, Object> status = new HashMap<>();
        status.put(STATUS, option);

        HttpCallback<HttpData<Void>> callback = new HttpCallback<HttpData<Void>>(null) {
            @Override
            public void onStart(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity){
                    ((AppActivity) getContext()).showDialog("执行中...");
                }
            }

            @Override
            public void onSucceed(HttpData<Void> result) {
                mDevice.setLight(light);
                boolean isOpen = light > 0;
                if(isOpen != mDevice.getIsOpen()){
                    mDevice.setIsOpen(isOpen);
                    colorTemperatureSeekBar.setOpenState(mDevice.getIsOpen());
                    setStatusBySwitch(mDevice.getIsOpen());
                }
                LLDeviceDBManager.getInstance(getContext()).put(mDevice);
                refreshDeviceStateByLocal();
            }

            @Override
            public void onFail(Exception e) {
                colorTemperatureSeekBar.setColorValue(mDevice.getLight());
                colorTemperatureSeekBar.setOpenState(mDevice.getLight() == 0 ? false : mDevice.getIsOpen());
                ToastUtils.show(R.string.exec_failure);
            }

            @Override
            public void onEnd(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity) {
                    ((AppActivity) getContext()).hideDialog();
                }
            }
        };
        LLHttpManager.operationDevice((LifecycleOwner) getContext(), mDevice.getDeviceSerialNo(), status, callback);
    }

    private void changeColor(int colorValue){
        int red = ( colorValue & 0xff0000 ) >> 16;
        int green = ( colorValue & 0xff00 ) >> 8;
        int blue = colorValue & 0xff;
        tvFloorRoom.setText("R:"+ red + ";G:"+ green+";B:"+blue);
        Map<String, Object> option = new HashMap<>();
        option.put(LLDeviceUtil.RED, red);
        option.put(LLDeviceUtil.GREEN, green);
        option.put(LLDeviceUtil.BLUE, blue);
        Map<String, Object> status = new HashMap<>();
        status.put(STATUS, option);

        HttpCallback<HttpData<Void>> callback = new HttpCallback<HttpData<Void>>(null) {
            @Override
            public void onStart(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity){
                    ((AppActivity) getContext()).showDialog("执行中...");
                }
            }

            @Override
            public void onSucceed(HttpData<Void> result) {
                mDevice.setRed(red);
                mDevice.setGreen(green);
                mDevice.setBlue(blue);
                LLDeviceDBManager.getInstance(getContext()).put(mDevice);
                refreshDeviceStateByLocal();
            }

            @Override
            public void onFail(Exception e) {
                ToastUtils.show(R.string.exec_failure);
            }

            @Override
            public void onEnd(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity) {
                    ((AppActivity) getContext()).hideDialog();
                }
            }
        };
        LLHttpManager.operationDevice((LifecycleOwner) getContext(), mDevice.getDeviceSerialNo(), status, callback);

    }
}
